package com.michael.ims.app.controller;

import com.michael.common.utils.Assert;
import com.michael.ims.app.controller.io.user.LoginReq;
import com.michael.ims.app.QTblUser;
import com.michael.ims.app.controller.io.user.QueryUserResp;
import com.michael.io.BaseUserInfoReq;
import com.michael.io.RespData;
import com.michael.io.UserInfo;
import com.michael.plugins.security.PasswordEncoder;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.Projections;
import com.querydsl.sql.SQLQueryFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@Api(tags = "用户管理")
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private SQLQueryFactory sqlQueryFactory;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @ApiOperation("用户登陆")
    @PostMapping("/login")
    @Transactional
    public RespData<UserInfo> login(@RequestBody @Valid LoginReq req) {
        QTblUser tblUser = QTblUser.tblUser;
        Tuple tuple = sqlQueryFactory.select(tblUser.id, tblUser.uuid, tblUser.password, tblUser.name, tblUser.email, tblUser.phone)
                .from(tblUser)
                .where(tblUser.account.eq(req.getUserName()))
                .fetchOne();
        Assert.isNull(tuple, "100001");
        Assert.isFalse(passwordEncoder.matches(req.getPassword(), tuple.get(tblUser.password)), "100002");
        UserInfo data = new UserInfo();
        data.setId(tuple.get(tblUser.id));
        data.setUuid(tuple.get(tblUser.uuid));
        data.setPhone(tuple.get(tblUser.phone));
        data.setEmail(tuple.get(tblUser.email));
        data.setName(tuple.get(tblUser.name));
        return new RespData<>(data);
    }

    @ApiOperation("获取用户信息")
    @PostMapping("/query")
    @Transactional
    public RespData<QueryUserResp> query(@RequestBody @Valid BaseUserInfoReq req) {
        UserInfo user = req.getUser();
        QTblUser tblUser = QTblUser.tblUser;
        QueryUserResp queryUserResp = sqlQueryFactory.select(Projections.bean(QueryUserResp.class,
                tblUser.id, tblUser.uuid, tblUser.name, tblUser.email, tblUser.phone))
                .from(tblUser)
                .where(tblUser.id.eq(user.getId()))
                .fetchOne();
        Assert.isNull(queryUserResp, "100001");
        return new RespData<>(queryUserResp);
    }
}
